package org.pb.order.service.impl;

import org.pb.basic.service.impl.BaseServiceImpl;
import org.pb.basic.utils.CodeGenerateUtils;
import org.pb.basic.utils.LoginContextUtils;
import org.pb.basic.utils.PageList;
import org.pb.order.domain.AdoptOrder;
import org.pb.order.domain.OrderAddress;
import org.pb.order.mapper.AdoptOrderMapper;
import org.pb.order.mapper.OrderAddressMapper;
import org.pb.order.query.AdoptOrderQuery;
import org.pb.order.service.IAdoptOrderService;
import org.pb.org.mapper.EmployeeMapper;
import org.pb.pay.constants.PayConstants;
import org.pb.pay.domain.PayBill;
import org.pb.pay.mapper.PayBillMapper;
import org.pb.pay.service.IPayBillService;
import org.pb.pet.domain.Pet;
import org.pb.pet.mapper.PetMapper;
import org.pb.user.domain.LoginInfo;
import org.pb.user.domain.User;
import org.pb.user.domain.UserAddress;
import org.pb.user.mapper.UserAddressMapper;
import org.pb.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 领养订单的业务层实现类
 * @author pb
 */
@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder, AdoptOrderQuery> implements IAdoptOrderService {

    @Autowired
    private AdoptOrderMapper adoptOrderMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IPayBillService payBillService;

    @Override
    @Transactional
    public String submit(Map<String, Long> map, HttpServletRequest request) {
        /*
            创建宠物领养订单：
            1. 领养订单部分
                1. 设置订单状态为0，未完成
                2. 设置订单最迟支付时间 【30分钟】
                3. 设置订单最迟确认时间 【30分钟】
                4. 设置订单的唯一编号orderSn、对应的支付唯一编号paySn【利用codeGenerateUtils】
                5. 将上述参数和pet_id、user_id、shop_id、price设置到对应的存储对象中
                6. 保存领养订单
            2. 订单地址部分：
                1. 获取到领养订单id、领养订单唯一编号保存到订单地址对象中
                2. 设置当前时间为订单地址创建时间
                3. 通过address_id获取到对应的用户地址信息，并保存到订单地址对象中
            3. 宠物下架：
                完成了订单创建之后，需要下架宠物,设置宠物状态为0，表示已下架；同时将当前时间设置为下架时间。
         */

        // 通过loginContextUtils获取到loginInfo信息，进而获取到对应的用户id
        LoginInfo loginInfo = LoginContextUtils.getLoginInfo(request);
        User user = userMapper.getUserByLoginInfo(loginInfo);
        // 通过pet_id获取到对应的宠物信息
        Pet pet = petMapper.loadById(map.get("pet_id"));
        // 创建领养订单对象，用于储存领养订单数据
        AdoptOrder adoptOrder = new AdoptOrder();
        // 1.1 设置订单状态
        adoptOrder.setState(0);
        // 1.2 设置最迟支付时间
        adoptOrder.setLastPayTime(new Date(System.currentTimeMillis() + 30 * 60 * 1000));
        // 1.3 设置最迟确认时间
        if (adoptOrder.getLastConfirmTime() != null) {
            // 这里因为用户点击了支付，所以已经确认，默认最迟时间为当前时间
            adoptOrder.setLastConfirmTime(new Date(System.currentTimeMillis()));
        }
        // 1.4 获取到唯一订单编号【10位】
        String orderSn = CodeGenerateUtils.generateOrderSn(10);
        adoptOrder.setOrderSn(orderSn);
        // 1.5 获取到唯一支付订单编号
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        adoptOrder.setPaySn(paySn);
        // 1.5 设置其余参数
        adoptOrder.setUser_id(user.getId());
        adoptOrder.setPet_id(pet.getId());
        adoptOrder.setShop_id(pet.getShop_id());
        adoptOrder.setPrice(pet.getSaleprice());
        adoptOrder.setDigest("[摘要]对" + pet.getName() + "的领养订单");
        // 1.6 保存订单信息
        adoptOrderMapper.save(adoptOrder);

        // 2.1 通过address_id获取到对应的用户地址信息，并保存到订单地址对象中
        UserAddress userAddress = userAddressMapper.loadById(map.get("address_id"));
        OrderAddress orderAddress = new OrderAddress();
        orderAddress.setAddress(userAddress.getAddress());
        orderAddress.setContacts(userAddress.getContacts());
        orderAddress.setAreaCode(userAddress.getAreaCode());
        orderAddress.setCreateTime(new Date());
        orderAddress.setEmail(userAddress.getEmail());
        orderAddress.setFullAddress(userAddress.getFullAddress());
        orderAddress.setPhone(userAddress.getPhone());
        orderAddress.setPhoneBack(userAddress.getPhoneBack());
        orderAddress.setPostCode(userAddress.getPostCode());
        orderAddress.setTel(userAddress.getTel());
        // 2.2 将订单编号和订单id设置到订单地址存储对象中
        orderAddress.setOrder_id(adoptOrder.getId());
        orderAddress.setOrderSn(adoptOrder.getOrderSn());
        // 2.3 保存订单地址
        orderAddressMapper.save(orderAddress);

        // 3.1 修改宠物的状态和下架时间
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("offsaleTime", new Date());
        updateMap.put("id", pet.getId());
        petMapper.offSale(updateMap);

        // 4. 支付信息，创建对应的支付账单信息对象
        PayBill payBill = new PayBill();
        payBill.setDigest(adoptOrder.getDigest());
        payBill.setMoney(adoptOrder.getPrice());
        payBill.setLastPayTime(new Date(System.currentTimeMillis() + 30 * 60 * 1000));
        payBill.setPayChannel(map.get("pay_method"));
        payBill.setCreateTime(new Date());
        payBill.setUnionPaySn(paySn);
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT);
        payBill.setBusinessKey(adoptOrder.getId());
        payBill.setUser_id(adoptOrder.getUser_id());
        payBill.setNickName(user.getUsername());
        payBill.setShop_id(adoptOrder.getShop_id());
        // 保存订单信息
        payBillService.save(payBill);
        // 获取到返回结果
        String resultData = payBillService.getResultData(payBill);
        return resultData;
    }

    @Override
    public PageList<AdoptOrder> adminQuery(AdoptOrderQuery query, HttpServletRequest request) {
        // 获取到当前登录状态
        LoginInfo loginInfo = LoginContextUtils.getLoginInfo(request);
        // 判断登录信息类型 0【平台员工】 1【用户】
        if (loginInfo.getType() == 0) {
            // 类型为0，表示为平台员工,将shop_id设置到query中
            query.setShopId(employeeMapper.getByLogInfoId(loginInfo).getShop_id());
        } else {
            // 类型为1，表示为用户，将user_id设置到query中
            query.setUserId(userMapper.getByLoginInfo(loginInfo));
        }
        query.setState(0);
        // 返回查询结果
        PageList<AdoptOrder> pageList = new PageList<>();
        pageList.setTotals(adoptOrderMapper.countQuery(query));
        pageList.setData(adoptOrderMapper.findByQuery(query));
        return pageList;
    }
}
